<html>
  <meta charset="UTF-8">
  <title>登录页面</title>
  <head>
    <meta charset="UTF-8">
    <title>登录页面异步交互</title>
    <script type="text/javascript" src="https://lib.baomitu.com/jquery/3.3.1/jquery.js"></script>
  </head>
  <body>
  <form id="xx">
    <table>
      <tr>
        <td>用户名</td>
        <td><input type="text" name="name" id="username"/></td>
      </tr>
      <tr>
        <td>密码</td>
        <td><input type="text" name="pwd" id="password"/></td>
      </tr>
      <tr>
        <td><input type="button" value="登录"   onclick="login()"></td>
      </tr>
    </table>
  </form>
  </body>
  <script>
    function login() {
      var username = document.getElementById("username").value;
      var password = document.getElementById("password").value;
      //创建Ajax对象
      var http=new XMLHttpRequest();
      //设置Ajax的请求地址与请求方式
      http.open("post","http://localhost:8080/UserLogin2Servlet");
      //设置请求的参数格式的类型（post请求必须要设置）
      // http.setRequestHeader('Content-type','application/x-www-form-urlencoded') username=123&password=344
      http.setRequestHeader('Content-type','application/json')
      //发送请求
      http.send(JSON.stringify({
          username:username,
          password:password
      }));
      //获取响应数据
      http.onreadystatechange=function () {
        //readyState 0=>初始化 1=>载入 2=>载入完成 3=>解析 4=>完成
        if(this.readyState==4&&this.status==200){
          var responseText=this.responseText
          console.log('返回结果：'+responseText)
          var result=JSON.parse(responseText);
          if(result.success){
            alert('登录成功')
            window.location.href="http://localhost:8080/loginAuth/main.html";
          }else {
             alert(result.errorMsg)
          }
        }
      }
    }
  </script>
</html>
